package com.breadenglish.cms.api.app.sys.service.impl;

import com.breadenglish.cms.api.app.common.utils.StringUtils;
import com.breadenglish.cms.api.app.dao.ComboboxDao;
import com.breadenglish.cms.api.app.domain.model.ComboboxData;
import com.breadenglish.cms.api.app.sys.service.ComboboxService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 下拉列表生成服务实现
 * User: guoyao
 * Date: 13-12-23
 * Time: 下午2:57
 */
@Service("comboboxService")
public class ComboboxServiceImpl implements ComboboxService {

    @Resource
    private ComboboxDao comboboxDao;

    @Override
    public List<ComboboxData> queryDictByClass(String classId, String selected) throws Throwable {
        List<ComboboxData> comboboxDataList = comboboxDao.queryDictByClass(StringUtils.isBlank(classId) ? null : classId);
        // 设置列表默认值
        return comboboxSelected(comboboxDataList, selected);
    }


    @Override
    public List<ComboboxData> queryProvince(String districtId, String selected) throws Throwable {
        List<ComboboxData> comboboxDataList = comboboxDao.queryProvince(StringUtils.isBlank(districtId) ? null : Integer.parseInt(districtId));
        // 设置列表默认值
        return comboboxSelected(comboboxDataList, selected);
    }

    @Override
    public List<ComboboxData> queryCity(String provinceId, String selected) throws Throwable {
        List<ComboboxData> comboboxDataList = comboboxDao.queryCity(StringUtils.isBlank(provinceId) ? null : provinceId);
        // 设置列表默认值
        return comboboxSelected(comboboxDataList, selected);
    }

    @Override
    public List<ComboboxData> queryArea(String cityId, String selected) throws Throwable {
        List<ComboboxData> comboboxDataList = comboboxDao.queryArea(StringUtils.isBlank(cityId) ? null : cityId);
        // 设置列表默认值
        return comboboxSelected(comboboxDataList, selected);
    }


    /**
     * 设置列表默认选择项
     *
     * @param comboboxDataList 下拉列表
     * @param selected         默认选中
     * @return 下拉列表
     */
    private List<ComboboxData> comboboxSelected(List<ComboboxData> comboboxDataList, String selected) throws Throwable {
        List<ComboboxData> comboboxDatas = new ArrayList<ComboboxData>();
        ComboboxData selectedData = new ComboboxData();
        selectedData.setId("");
        selectedData.setText("请选择");
        comboboxDatas.add(selectedData);
        comboboxDatas.addAll(comboboxDataList);

        // 判断是否有默认选择
        if (StringUtils.isNotBlank(selected)) {
            for (ComboboxData data : comboboxDatas) {
                // 设置默认选择项
                if (selected.equals(data.getId())) {
                    data.setSelected(true);
                    break;
                }
            }
        } else {
            comboboxDatas.get(0).setSelected(true);
        }
        return comboboxDatas;
    }

}
